package com.ssm.web;

import com.ssm.Entity.Folder;
import com.ssm.service.FileService;
import com.ssm.service.FolderService;
import com.ssm.service.UserService;
import com.ssm.vo.FileClassificationVo;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private FolderService folderService;

    @Resource
    private UserService userService;

    @RequestMapping("/fileUp")
    @ResponseBody
    public ModelAndView upload(MultipartFile file, HttpServletRequest request, HttpSession session1) throws IOException {
        /*
         * MultipartFile:来源于SpringMVC这个框架，对应页面中的file输入流
         */

        int userId = (int) session1.getAttribute("loggedIn");
        Folder folder = (Folder) session1.getAttribute("folder");
        int folderId = folder.getFolderId();
        //获取到原始的文件名
        String fileRealName = file.getOriginalFilename(); //通过输入流对象，获取文件名,上传的真实文件名
        String fileSaveName = null; //保存的文件名

        // 从配置文件中获取文件上传路径
        //String dir = request.getServletContext().getInitParameter("file.upload.path");
        //if (dir == null) {
        //    dir = "/JAvaproject/homework2/src/main/webapp/files"; // 默认路径
        //}
        String dir = "/JAvaproject/files"; // 默认路径

        double fileSize = file.getSize() / 1024; //获取上传文件的大小，单位为KB
        double folderSize = folder.getFolderSize(); //获取文件夹的大小
        double newFolderSize = folderSize - fileSize;
        if (newFolderSize < 0) { //判断文件大小是否超过文件夹大小
           ModelAndView modelAndView = new ModelAndView("error");
            return modelAndView;
        }

        //获取文件的后缀
        String suffix = fileRealName.substring(fileRealName.lastIndexOf("."));

            String uuid = UUID.randomUUID().toString();//生成一个新的文件名，避免文件同名出现文件覆盖的现象
            fileSaveName = uuid + suffix; //拼接新的文件名
            String pathname = dir + "/" + uuid + suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(pathname));


            com.ssm.Entity.File fille = new com.ssm.Entity.File();
            fille.setFileRealName(fileRealName);
            fille.setFileSaveName(fileSaveName);
            fille.setFileSize(fileSize);
            fille.setFolderId(folderId);
            fille.setUserId(userId);
            fille.setTimes(0);
            int result = fileService.createFile(fille); //调用接口中 定义的数据库操作方法
            if (result != 1) {
                throw new RuntimeException("添加文件失败");
            }

            folder.setFolderSize(newFolderSize);
            int res = fileService.updateFolderSize(folder);
            if (res != 1) {
                throw new RuntimeException("修改文件夹大小失败");
            }
            return new ModelAndView("redirect:/folder/showFolder");

    }

    @RequestMapping("/showFileDownList")
    @ResponseBody
    public ModelAndView showfileDownList( HttpSession session1){
        //获取指定路径下的所有可下载的文件名
        String path = "/JAvaproject/files";
        System.out.println(path);
        /**
         * 路径之下的查询操作 所有文件
         */
        File filepath = new File(path);
        String[] fileNames1 = filepath.list(); //查询该路径下的所有文件

        HashMap<String, List<FileClassificationVo>> map = new HashMap<>();

        for (String fileName:fileNames1 ) {
            //获取文件后缀名
            String suffix = fileName.substring(fileName.lastIndexOf("."));

            List<FileClassificationVo> list = map.getOrDefault(suffix, new ArrayList<>());

            Integer times = fileService.selectFileTimesByFileName(fileName);
            FileClassificationVo vo = new FileClassificationVo(times, fileName);
            list.add(vo);
            map.put(suffix, list);

        }
        session1.setAttribute("ClassificationVoMap",map);
        return new ModelAndView("download");
    }

    @RequestMapping("download")
    @ResponseBody
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException{
        int times = fileService.selectFileTimesByFileName(fileName);
        times = times + 1;
        fileService.updateFileTimesByFileName(fileName,times);
        //下载是2进制的响应输出，必须设置响应头信息
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //创建输出流 二进制
        ServletOutputStream os = response.getOutputStream();

        //根据提供fileName，定位下载的文件
        //确定的下载文件的绝对路径
        String path = "/JAvaproject/files";
        //将要下载的文件生成为File对象
        File file = new File(path, fileName);



        //使用第三方的下载工具
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();


    }
}
